package com.zl.learning.io.test.com.ronsoft.books.nio.regex;

/**
 * Created by zhaolei on 2017/4/26.
 */

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Exercise the replacement capabilities of the java.util.regex.Matcher
 * class. Run this code from the command line with three or more arguments.
 * 1) First argument is a regular expression
 * 2) Second argument is a replacement string, optionally with capture
 * group references ($1, $2, etc)
 * 3) Any remaining arguments are treated as input strings to which the
 * regular expression and replacement strings will be applied.
 * The effect of calling replaceFirst( ) and replaceAll( ) for each input
 * string will be listed.
 * <p>
 * Be careful to quote the commandline arguments if they contain spaces
 * or special characters.
 *
 * @author Ron Hitchens (ron@ronsoft.com)
 */
public class RegexReplace {
    public static void main(String[] argv) {
// 完整性检查，至少需要三个参数
        if (argv.length < 3) {
            System.out.println("usage: regex replacement input ...");
            return;
        }
// 用助词符号名保存正则及替换字符串
        String regex = argv[0];
        String replace = argv[1];
// 编译表达式；一次只能编译一个
        Pattern pattern = Pattern.compile(regex);
// 得到Matcher实例，暂时先使用虚设的输入字符串
        Matcher matcher = pattern.matcher("");
// 打印输出用于参考
        System.out.println(" regex: '" + regex + "'");
        System.out.println(" replacement: '" + replace + "'");
// 对各个剩余的参数字符串应用正则/替换
        for (int i = 2; i < argv.length; i++) {
            System.out.println("------------------------");
            matcher.reset(argv[i]);
            System.out.println(" input: '"
                    + argv[i] + "'");
            System.out.println("replaceFirst( ): '"
                    + matcher.replaceFirst(replace) + "'");
            System.out.println(" replaceAll( ): '"
                    + matcher.replaceAll(replace) + "'");
        }
    }
}